package 多线程.案例.myTimer;
import java.util.concurrent.PriorityBlockingQueue;

//模拟实现定时器
public class MyTimer{
    //线程安全的优先级队列, 小根堆
    PriorityBlockingQueue<MyTask> heap = new PriorityBlockingQueue<>();
    static Object lock = new Object();

    public void schedule(Runnable command, long after) {
        MyTask task = new MyTask(command, after);
        synchronized (lock) { //保证下面在执行 wait 之前, 这里不会插入新任务
            heap.put(task);
            lock.notify();
        }
    }

    public MyTimer() {
        Thread thread = new Thread(() -> {
            while (true) {
                try {
                    synchronized (lock) {
                        while (heap.isEmpty()) {
                            lock.wait();
                        }
                        MyTask task = heap.take();
                        if (System.currentTimeMillis() - task.getTime() > 0) {
                            heap.put(task); //放置元素后, 再等待一定的时间
                            lock.wait(task.getTime() - System.currentTimeMillis());
                        } else {
                            task.run();
                        }
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });

        thread.start();
    }
}






